package com.dlb.andorid.activity;

import android.content.Context;
import android.os.Bundle;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dlb.andorid.App;
import com.dlb.andorid.ProductAdapter;
import com.dlb.andorid.R;
import com.dlb.andorid.XContract;
import com.dlb.andorid.XServerMsg;
import com.dlb.andorid.bean.ArgAddOrder;
import com.dlb.andorid.bean.ArgCar;
import com.dlb.andorid.bean.Comment;
import com.dlb.andorid.bean.Order;
import com.dlb.andorid.bean.ProductBean;
import com.dlb.andorid.bean.ProductDetailBean;
import com.dlb.andorid.bean.ServerResult;
import com.dlb.andorid.presenter.ProductDetailPresenter;
import com.kwan.xframe.mvp.presenter.BasePresenter;
import com.kwan.xframe.mvp.view.activity.BaseCommonActivity;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ProductDetailActivity extends BaseCommonActivity implements XContract.IProductDetailView {

	private ProductDetailPresenter mPresenter;
	private long mId;
	private View iv_back;
	private ImageView iv_icon, iv_fav;
	private View tv_add_to_car, tv_buy;
	private int addCarNum = 1;

	private View tv_minus, tv_add;
	private TextView tv_num, tv_price, tv_price_old;

	private TextView tv_title_name, tv_des, tv_remain_num, tv_buy_num, tv_gg_name, tv_gg_price,
			tv_gg_jhl, tv_gg_bzq, tv_gg_bctj, tv_buy_name,tv_price_wholesale;

	@Override
	protected void beForeSetContentView() {
		super.beForeSetContentView();
		mId = (long) getIntentData("id");
	}

	@Override
	protected BasePresenter getBasePresenter() {
		mPresenter = new ProductDetailPresenter(this);
		return mPresenter;
	}

	RecyclerView rv_rec;

	BaseQuickAdapter<ProductBean, BaseViewHolder> mRecAdapter;
	BaseQuickAdapter<String, BaseViewHolder> mCarAdapter;

	private ArrayList<ProductBean> mProducts = new ArrayList<>();

	@Override
	protected void initViews() {
		super.initViews();
		tv_buy = findViewById(R.id.tv_buy);
		iv_fav = findViewById(R.id.iv_fav);
		tv_title_name = findViewById(R.id.tv_title_name);
		tv_des = findViewById(R.id.tv_des);
		tv_remain_num = findViewById(R.id.tv_remain_num);
		tv_buy_num = findViewById(R.id.tv_buy_num);
		tv_gg_name = findViewById(R.id.tv_gg_name);
		tv_gg_price = findViewById(R.id.tv_gg_price);
		tv_gg_jhl = findViewById(R.id.tv_gg_jhl);
		tv_gg_bzq = findViewById(R.id.tv_gg_bzq);
		tv_gg_bctj = findViewById(R.id.tv_gg_bctj);
		tv_buy_name = findViewById(R.id.tv_buy_name);

		tv_price = findViewById(R.id.tv_price);
		tv_price_old = findViewById(R.id.tv_price_old);
		tv_price_wholesale = findViewById(R.id.tv_price_wholesale);


		tv_add_to_car = findViewById(R.id.tv_add_to_car);
		tv_minus = findViewById(R.id.tv_minus);
		tv_add = findViewById(R.id.tv_add);
		tv_num = findViewById(R.id.tv_num);
		iv_icon = findViewById(R.id.iv_icon);
		iv_back = findViewById(R.id.iv_back);

		iv_back.setOnClickListener(this);
		tv_add_to_car.setOnClickListener(this);
		tv_minus.setOnClickListener(this);
		tv_add.setOnClickListener(this);
		iv_fav.setOnClickListener(this);
		tv_buy.setOnClickListener(this);

		rv_rec = findViewById(R.id.rv_rec);
		rv_rec.setLayoutManager(new GridLayoutManager(this, 2, LinearLayoutManager.VERTICAL, false));
		rv_rec.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		rv_rec.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		rv_rec.setLayerType(View.LAYER_TYPE_NONE, null);

		rv_rec.setHasFixedSize(true);
		rv_rec.setItemAnimator(null);
		rv_rec.setNestedScrollingEnabled(false);
		mRecAdapter = new ProductAdapter(mProducts);

		mRecAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
			@Override
			public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
				Bundle bundle = new Bundle();
				bundle.putLong("id", mProducts.get(position).getId());
				go2Activity(ProductDetailActivity.class, bundle, false);
			}
		});

		mRecAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
			@Override
			public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
				//toastMsg(""+mProducts.get(position).getId());
				Log.e("kwan", "car:" + mProducts.get(position).getId());
				if (view.getId() == R.id.iv_car) {
					Log.e("kwan", "car:" + mProducts.get(position).getId());
					showProgress("");
					mPresenter.addCar(mProducts.get(position).getId(), App.mUserInfo.getUid(), 1, mProducts.get(position).getType_id(), mProducts.get(position).getSale_price());
				}

			}
		});

		rv_rec.setAdapter(mRecAdapter);
	}

	@Override
	protected void initData() {
		showProgress("");
		mPresenter.getDetail(mId);
		mPresenter.getRecommend();
	}


	@Override
	protected int getTopViewId() {
		return 0;
	}

	@Override
	protected int getMainViewId() {
		return R.layout.activity_product_detail;
	}

	@Override
	protected int getBottomViewId() {
		return 0;
	}

	@Override
	protected String getTitleTxt() {
		return null;
	}

	@Override
	public String getPageName() {
		return null;
	}


	Banner banner;

	protected ProductDetailBean mDetailBean;


	@Override
	public void getDetailSuccess(ProductDetailBean data) {
		dismissProgress();
		mDetailBean = data;

		final TextView tv_banner_index = findViewById(R.id.tv_banner_index);

		tv_title_name.setText(data.getName());
		tv_des.setText(data.getDescribe());
		tv_remain_num.setText("库存：" + data.getTock_num());
		tv_buy_num.setText(data.getNum_buy() + "人已购");
		tv_gg_name.setText(data.getName() + data.getType_name());
		tv_gg_price.setText(data.getSale_price() + "");
		tv_gg_jhl.setText(data.getType_name());
		tv_gg_bzq.setText(data.getOvertime());
		tv_gg_bctj.setText(data.getPreservation());
		tv_buy_name.setText(data.getName() + " " + data.getType_name());
		tv_price.setText("¥ " + data.getSale_price());
		tv_price_old.setText("¥ " + data.getOrdinary_price());


		tv_price_wholesale.setVisibility(App.mUserInfo.getUser_group() == 6?View.VISIBLE:View.GONE);
		tv_price_wholesale.setText("¥ " + data.getWholesale_price());

		if (data.getCollect() == 1) {
			iv_fav.setImageResource(R.mipmap.iv_fav1);
		} else {
			iv_fav.setImageResource(R.mipmap.iv_fav0);
		}


		Comment comment = data.getComment();

		if (comment.getType() == 1) {
			findViewById(R.id.iv_comment_icon).setVisibility(View.VISIBLE);
			findViewById(R.id.tv_comment_num).setVisibility(View.VISIBLE);
			findViewById(R.id.ll_comment_phone_time).setVisibility(View.VISIBLE);

			mImageLoader.loadUrl(comment.getUser_pic(), (ImageView) findViewById(R.id.iv_comment_icon));


			((TextView) findViewById(R.id.tv_comment_phone)).setText(comment.getUser_nickname());
			((TextView) findViewById(R.id.tv_comment_content)).setText(comment.getComment_info());
			((TextView) findViewById(R.id.tv_comment_num)).setText("查看更多(" + comment.getNum() + ")");
			((TextView) findViewById(R.id.tv_comment_time)).setText(comment.getComment_time());
			((TextView) findViewById(R.id.tv_comment_content)).setGravity(Gravity.LEFT);

		} else {
			findViewById(R.id.ll_comment_phone_time).setVisibility(View.GONE);
			findViewById(R.id.iv_comment_icon).setVisibility(View.GONE);
			findViewById(R.id.tv_comment_num).setVisibility(View.GONE);
			((TextView) findViewById(R.id.tv_comment_content)).setText(comment.getMsg());
			((TextView) findViewById(R.id.tv_comment_content)).setGravity(Gravity.CENTER);
		}

		String[] tags = data.getTag_name().split(",");
		TextView tv_tag1 = findViewById(R.id.tv_tag1);
		TextView tv_tag2 = findViewById(R.id.tv_tag2);

		if (tags.length == 1) {

			tv_tag2.setVisibility(View.INVISIBLE);

			if (tags[0] == null || data.getTag_name().isEmpty()) {
				tv_tag1.setVisibility(View.INVISIBLE);
			} else {
				tv_tag1.setText(tags[0]);
			}

			Log.e("kwan", "tag:" + tags[0]);

		} else {

			if (tags[0] == null || data.getTag_name().isEmpty()) {
				tv_tag1.setVisibility(View.INVISIBLE);
			} else {
				tv_tag1.setText(tags[0]);
			}

			if (tags[1] == null || data.getTag_name().isEmpty()) {
				tv_tag2.setVisibility(View.INVISIBLE);
			} else {
				tv_tag2.setText(tags[1]);
			}

			Log.e("kwan", "tag:" + tags[0] + "  " + tags[1]);
		}


		mImageLoader.loadUrl(data.getPic_cover(), (ImageView) findViewById(R.id.iv_icon));

		final List<String> pics = Arrays.asList(data.getPic_info().split(","));


		try {
			if (pics == null || pics.size() == 0) return;
			if (banner == null) {
				tv_banner_index.setText(1 + "/" + pics.size());
				banner = findViewById(R.id.banner);
				//设置banner样式
				//banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
				//设置图片加载器
				banner.setImages(pics);
				banner.setImageLoader(new ImageLoader() {
					@Override
					public void displayImage(Context context, Object path, ImageView imageView) {
						//Glide 加载图片简单用法
						//Log.e("kwan", ((String) path).getPic_url());
						Glide.with(context).load(((String) path)).apply(App.mGildOptions).into(imageView);
					}
				});
				//设置图片集合

				//设置banner动画效果
				banner.setBannerAnimation(Transformer.DepthPage);
				//设置标题集合（当banner样式有显示title时）
				//banner.setBannerTitles(titles);
				//设置自动轮播，默认为true
				//banner.isAutoPlay(false);
				//设置轮播时间
				banner.setDelayTime(5000);
				//设置指示器位置（当banner模式中有指示器时）
				banner.setIndicatorGravity(BannerConfig.RIGHT);
				banner.setOnBannerListener(new OnBannerListener() {
					@Override
					public void OnBannerClick(int position) {
//						Bundle bundle = new Bundle();
//						bundle.putInt("mode", BaseWebActivity.MODE_WEB);
//						bundle.putString("url", result.get(position).getUrl());
//						bundle.putString("title", result.get(position).getTitle());
//						JLog.e("kwan", "banner click " + position);
//						go2Activity(WebActivity.class, bundle, false);
					}
				});

				//banner设置方法全部调用完毕时最后调用

				banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
					@Override
					public void onPageScrolled(int i, float v, int i1) {

					}

					@Override
					public void onPageSelected(int i) {

					}

					@Override
					public void onPageScrollStateChanged(int i) {
						tv_banner_index.setText((i + 1) + "/" + pics.size());
					}
				});
				banner.setFocusable(true);
				banner.setFocusableInTouchMode(true);
				banner.requestFocus();
				banner.start();

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void getRecommendProductsSuccess(List<ProductBean> data) {
		mProducts.clear();
		mProducts.addAll(data);
		mRecAdapter.notifyDataSetChanged();
	}

	@Override
	public void addCarSuccess(ServerResult data) {
		dismissProgress();
		toastMsg(data.getMsg());
	}

	@Override
	public void addFavSuccess(XServerMsg data) {
		dismissProgress();
		toastMsg(data.getMsg());
		iv_fav.setImageResource(R.mipmap.iv_fav1);
	}

	@Override
	public void addOrderSuccess(Order data) {
		Log.e("kwan", data.getOrder_no());
		Bundle bundle = new Bundle();
		bundle.putSerializable("order", data);
		go2Activity(OrderSureActivity.class, bundle, false);
	}


	@Override
	public void onClick(View v) {
		super.onClick(v);
		if (v == iv_back) {
			onBackPressed();
		} else if (v == tv_minus) {
			if (addCarNum > 1) {
				addCarNum = addCarNum - 1;
				tv_num.setText("" + addCarNum);
			}
		} else if (v == tv_add) {

			addCarNum = addCarNum + 1;
			tv_num.setText("" + addCarNum);
		} else if (v == tv_add_to_car && mDetailBean != null) {

			if (mDetailBean.getTock_num() == null || mDetailBean.getTock_num().isEmpty() || mDetailBean.getTock_num().equals("0")) {
				toastMsg("当前没有库存");
				return;
			}

			showProgress("");
			mPresenter.addCar(mId, App.mUserInfo.getUid(), addCarNum, mDetailBean.getType_id(), mDetailBean.getSale_price());
		} else if (v == iv_fav && mDetailBean != null) {

			if (mDetailBean.getCollect() == 0) {
				showProgress("");
				mPresenter.addFav(mId, 1);
			} else {
				toastMsg("已收藏");
			}

		} else if (v == tv_buy) {

			List<ArgCar> data = new ArrayList<>();
			ArgCar argCar = new ArgCar();
			argCar.setCommodity_id(mId);
			argCar.setCommodity_num(addCarNum);
			data.add(argCar);
			ArgAddOrder arg = new ArgAddOrder();
			arg.setUser_id(App.mUserInfo.getUid());
			arg.setData(data);
			mPresenter.addOrder(arg);

		}
	}
}

